package com.hxzy.common.util;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTCreator;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.auth0.jwt.interfaces.JWTVerifier;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.util.Map;

/**
 * 一定要加组件，声明这个类交给spring框架管理的
 */
@Log4j2
@Component
public class JwtUtil {

    @Value(value = "${token.security}")
    private String key;


    /**
     * 创建令牌
     * @param payload
     * @return
     */
    public  String createToken(Map<String, Object> payload) {
        JWTCreator.Builder builder = JWT.create();
        //放到json
        builder.withClaim("value",payload);

        return builder  .sign(Algorithm.HMAC256(key));
    }





    /**
     * 验证密码有效性
     * @param token
     * @return
     */
    public  DecodedJWT parseToken(String token) {
        try {
            JWTVerifier build = JWT.require(Algorithm.HMAC256(key)).build();
            return build.verify(token);
        }catch(Exception e){
            log.error(e);
            //隐藏异常
            return null;
        }
    }



}
